package com.ldr.custom.spring.v3.context.support;

import com.ldr.custom.spring.v3.beans.GPBeanDefinition;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * bean定义读取器
 * 用来对配置文件进行查找，解析，读取
 */
public class GPBeanDefinitionReader {


    private Properties config = new Properties();

    private List<String> registerBeanClasses = new ArrayList<>();

    private final String SCAN_PACKAGE = "scan-package";

    public GPBeanDefinitionReader(String... locations) {

        InputStream in = this.getClass().getClassLoader().getResourceAsStream(locations[0].replace("classpath:", ""));
        try {
            config.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        doScanner(this.config.getProperty(SCAN_PACKAGE));
    }


    public List<String> loadBeanDefinitions() {
        return this.registerBeanClasses;
    }

    /**
     * 每注册一个className，就返回一个BeanDefinition
     * 我们自己包装的，只是为了对配置信息进行包装
     */
    public GPBeanDefinition registerBean(String className) {
        if (this.registerBeanClasses.contains(className)) {
            GPBeanDefinition GPBeanDefinition = new GPBeanDefinition();

            GPBeanDefinition.setBeanClassName(className);
            GPBeanDefinition.setFactoryBeanName(lowerFistCase(className.substring(className.lastIndexOf(".") + 1)));
            return GPBeanDefinition;
        }

        return null;
    }


    private void doScanner(String packageName) {

        URL resourceUrl = this.getClass().getResource("/"+packageName.replaceAll("\\.", "/"));

        File classDir = new File(resourceUrl.getFile());
        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                doScanner(packageName + "." + file.getName());
            } else {
                registerBeanClasses.add(packageName + "." + file.getName().replace(".class", ""));
            }

        }
    }

    public Properties getConfig() {
        return this.config;
    }

    private String lowerFistCase(String str) {
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
}
